//
//  WeiboCell.m
//  WXWeibo
//
//  Created by apple on 16/5/11.
//  Copyright © 2016年 zic_magic. All rights reserved.
//

#import "WeiboCell.h"
//#import "ThemeLabel.h"
#import "ThemeManager.h"
#import "NSDate+TimeAgo.h"
#import "WXLabel.h"
#import "WXPhotoBrowser.h"


@interface WeiboCell () <WXLabelDelegate, PhotoBrowerDelegate>

@end


@implementation WeiboCell

- (void)awakeFromNib {
    [super awakeFromNib];
    
    self.backgroundColor = [UIColor clearColor];
    self.iconImgView.layer.cornerRadius = 5;
    self.iconImgView.layer.borderColor = [UIColor grayColor].CGColor;
    self.iconImgView.layer.borderWidth = 0.5;
    self.iconImgView.layer.masksToBounds = YES;
    
    _nickNameLabel.colorName = @"Timeline_Name_color";
    _timeLabel.colorName = @"Timeline_Name_color";
    _sourceLabel.colorName = @"Timeline_Name_color";
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(themeChange) name:kThemeChangeNotification object:nil];

}

- (void)themeChange {
    
    //当属性改变时会自动调用setNeedsDisplay通知系统使用drawRect:重新绘制WXLabel
    self.weibotextLabel.textColor = [[ThemeManager shareManager] themeColorWithColorName:@"Timeline_Content_color"];
    
    self.retweetedTextLabel.textColor = [[ThemeManager shareManager] themeColorWithColorName:@"Detail_Content_color"];
    
    //改变超链接的颜色
//    [self.weiboTextLabel setNeedsDisplay];
    
}

- (void)setWeiboLayout:(WeiboCellLayout *)weiboLayout {
    
    _weiboLayout = weiboLayout;
    
    _nickNameLabel.text = _weiboLayout.weibo.user.name;
    _timeLabel.text = [self parseWeiboDate:_weiboLayout.weibo.created_at];

    _sourceLabel.text = [self parseSource:_weiboLayout.weibo.source];
    
    [_iconImgView sd_setImageWithURL:[NSURL URLWithString:_weiboLayout.weibo.user.profile_image_url]];
    self.weibotextLabel.text = _weiboLayout.weibo.text;
    self.weibotextLabel.textColor = [[ThemeManager shareManager] themeColorWithColorName:@"Timeline_Content_color"];

    if (_weiboLayout.weibo.thumbnail_pic != nil) {
        
//        [self.weiboImgView sd_setImageWithURL:[NSURL URLWithString:_weiboLayout.weibo.thumbnail_pic]];
        
        [self showImgWithUrls:_weiboLayout.weibo.pic_urls];
    }
    
    
    
    
    
    self.bottomLine.backgroundColor = [UIColor lightGrayColor];
    
    self.weibotextLabel.frame = _weiboLayout.weiboTextFrame;
    
//    self.weiboImgView.frame = _weiboLayout.weiboImgFrame;

    
    //转发微博配置
    if (_weiboLayout.weibo.retweeted_status != nil) {
        
        
        ThemeManager *manager = [ThemeManager shareManager];
        
        UIImage *image = [manager themeImageWithImageName:@"timeline_rt_border_9"];
        self.retweetedRect.image = [image stretchableImageWithLeftCapWidth:30 topCapHeight:20];
        
        if (_weiboLayout.weibo.retweeted_status.thumbnail_pic != nil) {
        
//            [self.weiboImgView sd_setImageWithURL:[NSURL URLWithString:_weiboLayout.weibo.retweeted_status.thumbnail_pic]];
            [self showImgWithUrls:_weiboLayout.weibo.retweeted_status.pic_urls];
        }
    
        self.retweetedTextLabel.text = _weiboLayout.weibo.retweeted_status.text;
        self.retweetedTextLabel.textColor = [[ThemeManager shareManager] themeColorWithColorName:@"Detail_Content_color"];

    }
    
    for (NSInteger i = 0; i < kImagesCount; i++) {
        
        UIImageView *imageView = self.weiboImgArr[i];
        imageView.frame = [_weiboLayout.weiboImgFrameArr[i] CGRectValue];
        
    }
    
    
    self.retweetedRect.frame = _weiboLayout.retweetedRectFrame;
//    self.retweetedImgView.frame = _weiboLayout.retweetedImgFrame;
    self.retweetedTextLabel.frame = _weiboLayout.retweetedTextFrame;

    self.bottomLine.frame = _weiboLayout.bottomLineFrame;

    
}

- (WXLabel *)weibotextLabel {
    
    if (_weibotextLabel == nil) {
        
        _weibotextLabel = [[WXLabel alloc] initWithFrame:CGRectZero];
        _weibotextLabel.font = [UIFont systemFontOfSize:16];
        _weibotextLabel.numberOfLines = 0;
        _weibotextLabel.wxLabelDelegate = self;
        
        [self.contentView addSubview:_weibotextLabel];
    }
    
    return _weibotextLabel;
    
}


- (UIImageView *)weiboImgView {
    
    if (_weiboImgView == nil) {
        _weiboImgView = [[UIImageView alloc] initWithFrame:CGRectZero];
//        [self.contentView addSubview:_weiboImgView];
        [self.contentView insertSubview:_weiboImgView aboveSubview:self.retweetedRect];
        
        
        
    }
    
    return _weiboImgView;
}


- (ThemeImageView *)retweetedRect {
    
    if (_retweetedRect == nil) {
        _retweetedRect = [[ThemeImageView alloc] initWithFrame:CGRectZero];
        
        [self.contentView addSubview:_retweetedRect];
    }
    
    return _retweetedRect;
}

- (WXLabel *)retweetedTextLabel {
    
    if (_retweetedTextLabel == nil) {
        _retweetedTextLabel = [[WXLabel alloc] initWithFrame:CGRectZero];
        _retweetedTextLabel.font = [UIFont systemFontOfSize:16];
        _retweetedTextLabel.numberOfLines = 0;
        _retweetedTextLabel.wxLabelDelegate = self;
        [self.contentView addSubview:_retweetedTextLabel];
    }
    return _retweetedTextLabel;
}


- (UIImageView *)bottomLine {
    if (_bottomLine == nil) {
        _bottomLine = [[UIImageView alloc] initWithFrame:CGRectZero];
        
        [self.contentView addSubview:_bottomLine];
    }
    return _bottomLine;
    
}

- (NSMutableArray *)weiboImgArr {
    
    if (_weiboImgArr == nil) {
        _weiboImgArr = [NSMutableArray array];
        
        for (NSInteger i = 0; i < 9; i++) {
            UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectZero];
            
            imgView.contentMode = UIViewContentModeScaleAspectFill;
            
            imgView.clipsToBounds = YES;
            
            imgView.userInteractionEnabled = YES;
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
            [imgView addGestureRecognizer:tap];
            imgView.tag = i;
            
            [self.contentView insertSubview:imgView aboveSubview:self.retweetedRect];
            [_weiboImgArr addObject:imgView];
        }
    }
    
 
    return _weiboImgArr;
}

#pragma mark - 图片的点击事件
- (void)tapAction:(UITapGestureRecognizer *)tap {
    

    [WXPhotoBrowser showImageInView:self.window selectImageIndex:tap.view.tag delegate:self];
    
    
}
#pragma mark - WXPhotoBrowser delegate
//需要显示的图片个数
- (NSUInteger)numberOfPhotosInPhotoBrowser:(WXPhotoBrowser *)photoBrowser {
    
    if (_weiboLayout.weibo.pic_urls.count > 0) {
        
        return _weiboLayout.weibo.pic_urls.count;
    } else {
        
        return _weiboLayout.weibo.retweeted_status.pic_urls.count;
    }
    
}

//返回需要显示的图片对应的Photo实例,通过Photo类指定大图的URL,以及原始的图片视图
- (WXPhoto *)photoBrowser:(WXPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    
    
    WXPhoto *photo = [[WXPhoto alloc] init];
    
    //拿到原图
    photo.srcImageView = self.weiboImgArr[index];
    
    //获取到大图的url
    
    NSArray *urls = nil;
    
    if (_weiboLayout.weibo.pic_urls.count > 0) {
        
        urls = _weiboLayout.weibo.pic_urls;
    } else {
        
        urls = _weiboLayout.weibo.retweeted_status.pic_urls;
    }
    
//    NSLog(@"%@",urls[index][@"thumbnail_pic"]);
    
    NSString *imgURLString = urls[index][@"thumbnail_pic"];
    
    //大图的url
    imgURLString = [imgURLString stringByReplacingOccurrencesOfString:@"thumbnail" withString:@"large"];
    
    photo.url = [NSURL URLWithString:imgURLString];
    
    return photo;
    
    
}

- (void)showImgWithUrls:(NSArray *)urls {
    
    
    for (NSInteger i = 0; i < urls.count; i++) {
        
        UIImageView *imgView = self.weiboImgArr[i];
        imgView.contentMode = UIViewContentModeScaleAspectFill;
        imgView.clipsToBounds = YES;
        [imgView sd_setImageWithURL:[NSURL URLWithString:urls[i][@"thumbnail_pic"]]];
        
        
    }
    
}

- (NSString *)parseWeiboDate:(NSString *)dataStr {
    
    NSString *formatter = @"E M d HH:mm:ss Z yyyy";
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = formatter;
    
    dateFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US"];
    NSDate *publicDate = [dateFormatter dateFromString:dataStr];
    
    
    
    return [publicDate timeAgo];
    
}

- (NSString *)parseSource:(NSString *)sourceStr {
    
    if (sourceStr.length <= 0) {
        return nil;
    }
    
    NSInteger start = [sourceStr rangeOfString:@">"].location;
    
    NSInteger end = [sourceStr rangeOfString:@"<" options:NSBackwardsSearch].location;
    
    return [sourceStr substringWithRange:NSMakeRange(start + 1, end - start -1)];
}

#pragma WXLabel Delegate 

- (NSString *)contentsOfRegexStringWithWXLabel:(WXLabel *)wxLabel {
    
    return @"(@[\\w-]{2,30}[\\s:])|(#[^#]+#)|(http(s)?://([A-Za-z0-9._-]+(/)?)*)";
}


- (UIColor *)linkColorWithWXLabel:(WXLabel *)wxLabel {
    
    return [[ThemeManager shareManager] themeColorWithColorName:@"Link_color"];
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
